<template>
  <div class="chat-container">
    <div class="chat-header">
      <div class="header-left">
        <div class="back-button" @click="goBack">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="back-icon">
            <line x1="19" y1="12" x2="5" y2="12"></line>
            <polyline points="12 19 5 12 12 5"></polyline>
          </svg>
        </div>
        <div class="title">AI 智能助手</div>
      </div>
      <div class="header-actions">

        <el-button 
          type="text" 
          size="small" 
          @click="clearHistory" 
          :disabled="chatMessages.length === 0"
          class="clear-button"
        >
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="clear-icon">
            <polyline points="3 6 5 6 21 6"></polyline>
            <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
            <line x1="10" y1="11" x2="10" y2="17"></line>
            <line x1="14" y1="11" x2="14" y2="17"></line>
          </svg>
          清空对话
        </el-button>
      </div>
    </div>
    
    <!-- 常用问题列表 -->
    <div class="faq-container">
      <div class="faq-header">
        <div class="faq-title">常用问题：</div>
        <div class="faq-actions">
          <el-tooltip content="点击问题复制到输入框" placement="top" :hide-after="1500">
            <div class="faq-mode-switch" :class="{ 'active': !directSendMode }" @click="directSendMode = false">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="faq-action-icon">
                <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
                <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
              </svg>
            </div>
          </el-tooltip>
          <el-tooltip content="点击问题直接发送" placement="top" :hide-after="1500">
            <div class="faq-mode-switch" :class="{ 'active': directSendMode }" @click="directSendMode = true">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="faq-action-icon">
                <line x1="22" y1="2" x2="11" y2="13"></line>
                <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
              </svg>
            </div>
          </el-tooltip>
          <el-tooltip content="添加自定义问题" placement="top" :hide-after="1500">
            <div class="faq-mode-switch" @click="showAddQuestionDialog = true">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="faq-action-icon">
                <line x1="12" y1="5" x2="12" y2="19"></line>
                <line x1="5" y1="12" x2="19" y2="12"></line>
              </svg>
            </div>
          </el-tooltip>
        </div>
      </div>
      <div class="faq-list">
        <div 
          v-for="(question, index) in commonQuestions" 
          :key="index" 
          class="faq-item"
          @click="directSendMode ? sendCommonQuestion(question) : setQuestion(question)"
        >
          <span>{{ question }}</span>
          <span 
            v-if="isCustomQuestion(question)" 
            class="delete-question" 
            @click.stop="confirmDeleteQuestion(question)"
            title="删除此问题"
          >
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="delete-icon">
              <line x1="18" y1="6" x2="6" y2="18"></line>
              <line x1="6" y1="6" x2="18" y2="18"></line>
            </svg>
          </span>
        </div>
      </div>
    </div>
    
    <div class="chat-body" ref="chatBodyRef">
      <div v-if="chatMessages.length === 0" class="empty-chat">
        <div class="welcome-message">
          <div class="ai-avatar">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <circle cx="12" cy="12" r="10"></circle>
              <path d="M12 16v-4"></path>
              <path d="M12 8h.01"></path>
            </svg>
          </div>
          <div class="welcome-text">
            <h3>您好！我是您的AI助手</h3>
            <p>我可以回答您关于养老服务的各种问题，请随时向我提问。</p>
          </div>
        </div>
      </div>
      <div v-else class="message-list">
        <div v-for="(message, index) in chatMessages" :key="index" :class="['message-item', message.role === 'user' ? 'user-message' : 'ai-message', message.isError ? 'error-message' : '']">
          <div class="message-avatar">
            <template v-if="message.role === 'user'">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                <circle cx="12" cy="7" r="4"></circle>
              </svg>
            </template>
            <template v-else-if="message.isError">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <circle cx="12" cy="12" r="10"></circle>
                <line x1="12" y1="8" x2="12" y2="12"></line>
                <line x1="12" y1="16" x2="12.01" y2="16"></line>
              </svg>
            </template>
            <template v-else>
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <circle cx="12" cy="12" r="10"></circle>
                <path d="M12 16v-4"></path>
                <path d="M12 8h.01"></path>
              </svg>
            </template>
          </div>
          <div class="message-content">
            <div class="message-text" v-html="formatMessage(message.content)"></div>
            <div class="message-footer">
              <div class="message-time">{{ formatTime(message.timestamp) }}</div>
              <div class="message-actions" v-if="message.role === 'assistant' && !message.isError">
                <div class="action-button" @click="copyMessageContent(message.content)" title="复制内容">
                  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="action-icon">
                    <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
                    <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
                  </svg>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-if="isLoading" class="loading-indicator">
        <div class="typing-indicator">
          <span></span>
          <span></span>
          <span></span>
        </div>
      </div>
    </div>
    <div class="chat-footer">
      <div class="input-container">
        <textarea 
          v-model="userInput" 
          class="chat-input" 
          placeholder="请输入您的问题..." 
          @keydown.enter.prevent="sendMessage"
          ref="inputRef"
          :disabled="isLoading"
        ></textarea>
        <div class="send-button" @click="sendMessage" :class="{ 'disabled': !userInput.trim() || isLoading }">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <line x1="22" y1="2" x2="11" y2="13"></line>
            <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
          </svg>
        </div>
      </div>
    </div>
  </div>

  <!-- 添加自定义问题对话框 -->
  <el-dialog
    v-model="showAddQuestionDialog"
    title="添加自定义问题"
    width="30%"
    :before-close="closeAddQuestionDialog"
  >
    <el-form :model="newQuestionForm" :rules="newQuestionRules" ref="newQuestionFormRef">
      <el-form-item prop="question" label="问题内容">
        <el-input 
          v-model="newQuestionForm.question" 
          placeholder="请输入问题内容..."
          maxlength="50"
          show-word-limit
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeAddQuestionDialog">取消</el-button>
        <el-button type="primary" @click="addCustomQuestion" :loading="newQuestionForm.loading">
          添加
        </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 图片查看器 -->
  <div v-if="showImageViewer" class="image-viewer-overlay" @click="closeImageViewer" @mousemove="onDrag" @mouseup="endDrag" @touchmove="onDrag" @touchend="endDrag">
    <div class="image-viewer-container" @click.stop>
      <!-- 加载指示器 -->
      <div v-if="isImageLoading" class="image-loading">
        <div class="loading-spinner"></div>
        <div class="loading-text">图片加载中...</div>
      </div>
      
      <img 
        :src="currentViewImage" 
        class="image-viewer-content" 
        :class="{ 'image-loading-hide': isImageLoading }"
        :style="{ transform: `translate(${imagePosition.x}px, ${imagePosition.y}px) scale(${imageScale})` }" 
        alt="查看图片" 
        @mousedown="startDrag" 
        @touchstart="startDrag"
        @load="onImageLoad"
        @error="onImageError"
        draggable="false"
      />
      
      <div class="image-viewer-controls">
        <div class="viewer-control-button" @click="zoomIn" title="放大">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <circle cx="11" cy="11" r="8"></circle>
            <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
            <line x1="11" y1="8" x2="11" y2="14"></line>
            <line x1="8" y1="11" x2="14" y2="11"></line>
          </svg>
        </div>
        <div class="viewer-control-button" @click="zoomOut" title="缩小">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <circle cx="11" cy="11" r="8"></circle>
            <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
            <line x1="8" y1="11" x2="14" y2="11"></line>
          </svg>
        </div>
        <div class="viewer-control-button" @click="resetZoom" title="重置">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M3 2v6h6"></path>
            <path d="M21 12A9 9 0 0 0 6 5.3L3 8"></path>
            <path d="M21 22v-6h-6"></path>
            <path d="M3 12a9 9 0 0 0 15 6.7l3-2.7"></path>
          </svg>
        </div>
        <div class="viewer-control-button close-button" @click="closeImageViewer" title="关闭">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <line x1="18" y1="6" x2="6" y2="18"></line>
            <line x1="6" y1="6" x2="18" y2="18"></line>
          </svg>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, computed } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { useRouter } from 'vue-router'

// 获取路由器实例
const router = useRouter()

// 聊天消息列表
const chatMessages = ref([])
// 用户输入
const userInput = ref('')
// 是否正在加载AI回复
const isLoading = ref(false)
// 聊天区域的引用，用于自动滚动
const chatBodyRef = ref(null)
// 输入框引用
const inputRef = ref(null)
// API基础URL
const baseURL = 'http://localhost:8081'
// 常用问题直接发送模式（true：直接发送，false：复制到输入框）
const directSendMode = ref(false)
// 显示添加问题对话框
const showAddQuestionDialog = ref(false)
// 图片查看器相关
const showImageViewer = ref(false)
const currentViewImage = ref('')
const imageScale = ref(1) // 图片缩放比例
const imagePosition = ref({ x: 0, y: 0 }) // 图片位置
const isDragging = ref(false) // 是否正在拖动
const dragStart = ref({ x: 0, y: 0 }) // 拖动开始位置
const isImageLoading = ref(false) // 图片加载状态
// 新问题表单引用
const newQuestionFormRef = ref(null)
// 新问题表单数据
const newQuestionForm = ref({
  question: '',
  loading: false
})
// 新问题表单验证规则
const newQuestionRules = {
  question: [
    { required: true, message: '请输入问题内容', trigger: 'blur' },
    { min: 2, max: 50, message: '问题长度应在2到50个字符之间', trigger: 'blur' }
  ]
}

// 常用问题列表（默认问题）
const defaultQuestions = [
  '获取所有医生信息',
  '查询排班信息',
  '查询指定日期的挂号信息',
  // '打开食堂页面'
]

// 从本地存储加载自定义问题
const loadCustomQuestions = () => {
  try {
    const savedQuestions = localStorage.getItem('ai_custom_questions')
    if (savedQuestions) {
      return JSON.parse(savedQuestions)
    }
    return []
  } catch (error) {
    console.error('从本地存储加载自定义问题失败:', error)
    return []
  }
}

// 保存自定义问题到本地存储
const saveCustomQuestions = (questions) => {
  try {
    localStorage.setItem('ai_custom_questions', JSON.stringify(questions))
  } catch (error) {
    console.error('保存自定义问题到本地存储失败:', error)
  }
}

// 合并默认问题和自定义问题
const commonQuestions = ref([...defaultQuestions, ...loadCustomQuestions()])

// 设置问题到输入框
const setQuestion = (question) => {
  userInput.value = question
  // 聚焦输入框
  if (inputRef.value) {
    inputRef.value.focus()
  }
}

// 直接发送常用问题
const sendCommonQuestion = (question) => {
  userInput.value = question
  sendMessage()
}

// 关闭添加问题对话框
const closeAddQuestionDialog = () => {
  showAddQuestionDialog.value = false
  newQuestionForm.value.question = ''
  if (newQuestionFormRef.value) {
    newQuestionFormRef.value.resetFields()
  }
}

// 添加自定义问题
const addCustomQuestion = async () => {
  if (!newQuestionFormRef.value) return
  
  await newQuestionFormRef.value.validate(async (valid) => {
    if (valid) {
      newQuestionForm.value.loading = true
      try {
        const newQuestion = newQuestionForm.value.question.trim()
        
        // 检查是否已存在相同问题
        if (commonQuestions.value.includes(newQuestion)) {
          ElMessage.warning('该问题已存在')
          return
        }
        
        // 获取当前自定义问题
        const customQuestions = loadCustomQuestions()
        
        // 添加新问题
        customQuestions.push(newQuestion)
        
        // 保存到本地存储
        saveCustomQuestions(customQuestions)
        
        // 更新显示的问题列表
        commonQuestions.value = [...defaultQuestions, ...customQuestions]
        
        ElMessage.success('添加成功')
        closeAddQuestionDialog()
      } catch (error) {
        console.error('添加自定义问题失败:', error)
        ElMessage.error('添加失败')
      } finally {
        newQuestionForm.value.loading = false
      }
    }
  })
}

// 判断是否为自定义问题
const isCustomQuestion = (question) => {
  return !defaultQuestions.includes(question)
}

// 确认删除问题
const confirmDeleteQuestion = (question) => {
  if (window.confirm(`确定要删除问题「${question}」吗？`)) {
    deleteCustomQuestion(question)
  }
}

// 删除自定义问题
const deleteCustomQuestion = (question) => {
  try {
    // 获取当前自定义问题
    const customQuestions = loadCustomQuestions()
    
    // 过滤掉要删除的问题
    const filteredQuestions = customQuestions.filter(q => q !== question)
    
    // 保存到本地存储
    saveCustomQuestions(filteredQuestions)
    
    // 更新显示的问题列表
    commonQuestions.value = [...defaultQuestions, ...filteredQuestions]
    
    ElMessage.success('删除成功')
  } catch (error) {
    console.error('删除自定义问题失败:', error)
    ElMessage.error('删除失败')
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 发送消息
const sendMessage = async () => {
  // 检查是否有输入内容
  if (!userInput.value.trim() || isLoading.value) return
  
  // 添加用户消息到列表
  const userMessage = {
    role: 'user',
    content: userInput.value,
    timestamp: new Date()
  }
  chatMessages.value.push(userMessage)
  
  // 清空输入框
  const tempInput = userInput.value
  userInput.value = ''
  
  // 滚动到底部
  await scrollToBottom()
  
  // 设置加载状态
  isLoading.value = true
  
  try {
    // 直接使用axios调用后端API获取AI回复
    const response = await axios.post(`${baseURL}/ai/chat`, { message: tempInput }, {
      timeout: 30000, // 设置超时时间为30秒
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    // 添加AI回复到列表
    let aiContent = response.data?.data || response.data || `您好,我是AI助手。您的问题是:${tempInput}。我们的系统正在处理您的请求，稍后会给您回复。`;
    
    // 检查回复中是否包含图片链接但没有正确格式化
    // 如果内容中包含图片URL但没有使用! `URL`格式，尝试自动格式化
    const imgUrlRegex = /(https?:\/\/\S+\.(jpg|jpeg|png|gif|webp|svg)(\?\S*)?)/gi;
    if (imgUrlRegex.test(aiContent) && !aiContent.includes('! `')) {
      console.log('检测到未格式化的图片链接');
      // 将URL转换为! `URL`格式
      aiContent = aiContent.replace(imgUrlRegex, '! `$1`');
    }
    
    const aiMessage = {
      role: 'assistant',
      content: aiContent,
      timestamp: new Date()
    }
    chatMessages.value.push(aiMessage)
    
    // 保存到本地存储，以防刷新页面丢失对话
    saveChatsToLocalStorage()
    
    // 滚动到底部
    await scrollToBottom()
  } catch (error) {
    console.error('获取AI回复失败:', error)
    // 添加错误消息
    // let errorMessage = '抱歉，服务器出现了问题，请稍后再试。'
    console.log('error', error)
    
    // 根据错误类型提供更具体的错误信息
    if (error.code === 'ECONNABORTED') {
      // errorMessage = '请求超时，服务器响应时间过长，请稍后再试。'
    } else if (error.response) {
      // 服务器返回了错误状态码
      errorMessage = `服务器返回了错误状态码 ${error.response.status}。`
      if (error.response.status === 401) {
        errorMessage = '您需要登录后才能使用AI助手功能。'
      } else if (error.response.status === 429) {
        errorMessage = '请求过于频繁，请稍后再试。'
      } else if (error.response.status >= 500) {
        errorMessage = '服务器内部错误，请联系管理员。'
      }
    } else if (error.request) {
      // 请求发出但没有收到响应
      errorMessage = '无法连接到服务器，请检查您的网络连接。'
    }
    
    chatMessages.value.push({
      role: 'assistant',
      content: errorMessage,
      timestamp: new Date(),
      isError: true
    })
    await scrollToBottom()
  } finally {
    isLoading.value = false
  }
}

// 复制消息内容
const copyMessageContent = (content) => {
  if (!content) return;
  
  // 创建一个临时的文本区域元素
  const textarea = document.createElement('textarea');
  
  // 处理图片链接，将 ! `URL` 格式保留为文本
  let processedContent = content.replace(/!\s*`([^`]+)`/g, '! `$1`');
  
  // 移除HTML标签，只保留纯文本
  const plainText = processedContent.replace(/<[^>]*>/g, '');
  textarea.value = plainText;
  document.body.appendChild(textarea);
  textarea.select();
  
  try {
    // 执行复制命令
    const successful = document.execCommand('copy');
    if (successful) {
      ElMessage.success('内容已复制到剪贴板');
    } else {
      ElMessage.error('复制失败');
    }
  } catch (err) {
    console.error('复制失败:', err);
    ElMessage.error('复制失败');
  }
  
  // 移除临时元素
  document.body.removeChild(textarea);
};

// 保存聊天记录到本地存储
const saveChatsToLocalStorage = () => {
  try {
    const chatsToSave = chatMessages.value.map(msg => ({
      ...msg,
      timestamp: msg.timestamp.toISOString() // 将Date对象转换为字符串
    }))
    // localStorage.setItem('ai_chat_history', JSON.stringify(chatsToSave))
  } catch (error) {
    console.error('保存聊天记录到本地存储失败:', error)
  }
}

// 从本地存储加载聊天记录
const loadChatsFromLocalStorage = () => {
  try {
    const savedChats = null ;
    // const savedChats = localStorage.getItem('ai_chat_history')
    if (savedChats) {
      const parsedChats = JSON.parse(savedChats)
      return parsedChats.map(msg => ({
        ...msg,
        timestamp: new Date(msg.timestamp) // 将字符串转换回Date对象
      }))
    }
    return []
  } catch (error) {
    console.error('从本地存储加载聊天记录失败:', error)
    return []
  }
}

// 加载历史对话记录
const loadChatHistory = async () => {
  // 首先尝试从本地存储加载
  const localChats = loadChatsFromLocalStorage()
  if (localChats.length > 0) {
    chatMessages.value = localChats
    await scrollToBottom()
    return
  }
  
  // 如果本地没有，则从服务器加载
  try {
    const response = await axios.get(`${baseURL}/ai/history`, {
      timeout: 10000,
      headers: {
        'Accept': 'application/json'
      }
    })
    if (response.data && response.data.data && Array.isArray(response.data.data)) {
      // 将历史记录添加到聊天消息列表
      chatMessages.value = response.data.data.map(msg => ({
        ...msg,
        timestamp: new Date(msg.timestamp)
      }))
      // 保存到本地存储
      saveChatsToLocalStorage()
      // 滚动到底部
      await scrollToBottom()
    }
  } catch (error) {
    console.error('获取历史对话记录失败:', error)
    // 不显示错误提示，因为可能是首次使用或服务器未配置
    // ElMessage.error('获取历史对话记录失败')
  }
}

// 清空对话历史
const clearHistory = async () => {
  try {
    // 清空本地存储
    localStorage.removeItem('ai_chat_history')
    
    // 尝试清空服务器存储
    try {
      await axios.delete(`${baseURL}/ai/history`)
    } catch (serverError) {
      console.error('清空服务器对话历史失败:', serverError)
      // 不显示错误，因为本地已清空
    }
    
    // 清空当前显示的消息
    chatMessages.value = []
    ElMessage.success('对话历史已清空')
  } catch (error) {
    console.error('清空对话历史失败:', error)
    ElMessage.error('清空对话历史失败')
  }
}

// 格式化消息内容，支持简单的换行和图片显示
const formatMessage = (content) => {
  if (!content) return '';
  
  // 先处理换行
  let formattedContent = content.replace(/\n/g, '<br>');
  
  // 处理图片链接格式: ! `URL`
  // 使用正则表达式匹配 ! `URL` 格式的图片链接
  // formattedContent = formattedContent.replace(/!\s*`([^`]+)`/g, (match, url) => {
  //   return `<img src="${url}" alt="图片" class="message-image" onclick="window.viewImage('${url}')" onerror="this.onerror=null; this.style.display='none'; this.insertAdjacentHTML('afterend', '<div class=\'image-error\'>图片加载失败: ${url}</div>')" />`;
  // });
  
  // 确保图片链接被正确处理，即使它们不完全符合格式
  // 查找可能的图片URL模式，如http(s)://开头，以常见图片扩展名结尾的链接
  formattedContent = formattedContent.replace(/(https?:\/\/\S+\.(jpg|jpeg|png|gif|webp|svg)(\?\S*)?)/gi, (match) => {
    if (!match.includes('<img')) { // 避免重复处理已转换为img标签的URL
      return `<img src="${match}" alt="图片" class="message-image" width="200" height="150" onclick="window.viewImage('${match}')" onerror="this.onerror=null; this.style.display='none'; this.insertAdjacentHTML('afterend', '<div class=\'image-error\'>图片加载失败</div>')" />`;
    }
    return match;
  });
  
  return formattedContent;
}

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (chatBodyRef.value) {
    chatBodyRef.value.scrollTop = chatBodyRef.value.scrollHeight
  }
}

// 查看图片（放大查看）
const viewImage = (url) => {
  isImageLoading.value = true // 开始加载
  currentViewImage.value = url
  showImageViewer.value = true
  // 重置缩放比例和位置
  imageScale.value = 1
  imagePosition.value = { x: 0, y: 0 }
}

// 图片加载完成
const onImageLoad = () => {
  isImageLoading.value = false
}

// 图片加载错误
const onImageError = () => {
  isImageLoading.value = false
  ElMessage.error('图片加载失败')
}

// 关闭图片查看器
const closeImageViewer = () => {
  showImageViewer.value = false
}

// 开始拖动图片
const startDrag = (e) => {
  if (e.touches) { // 移动设备
    isDragging.value = true
    dragStart.value = {
      x: e.touches[0].clientX - imagePosition.value.x,
      y: e.touches[0].clientY - imagePosition.value.y
    }
  } else { // 桌面设备
    isDragging.value = true
    dragStart.value = {
      x: e.clientX - imagePosition.value.x,
      y: e.clientY - imagePosition.value.y
    }
  }
}

// 拖动图片
const onDrag = (e) => {
  if (!isDragging.value) return
  
  if (e.touches) { // 移动设备
    imagePosition.value = {
      x: e.touches[0].clientX - dragStart.value.x,
      y: e.touches[0].clientY - dragStart.value.y
    }
  } else { // 桌面设备
    imagePosition.value = {
      x: e.clientX - dragStart.value.x,
      y: e.clientY - dragStart.value.y
    }
  }
}

// 结束拖动
const endDrag = () => {
  isDragging.value = false
}

// 放大图片
const zoomIn = () => {
  if (imageScale.value < 3) { // 限制最大缩放比例
    imageScale.value += 0.2
  }
}

// 缩小图片
const zoomOut = () => {
  if (imageScale.value > 0.5) { // 限制最小缩放比例
    imageScale.value -= 0.2
  }
}

// 重置缩放和位置
const resetZoom = () => {
  imageScale.value = 1
  imagePosition.value = { x: 0, y: 0 }
}

// 添加键盘事件监听
const handleKeyDown = (e) => {
  if (showImageViewer.value) {
    switch (e.key) {
      case 'Escape':
        closeImageViewer()
        break
      case '+':
      case '=':
        zoomIn()
        break
      case '-':
        zoomOut()
        break
      case '0':
        resetZoom()
        break
    }
  }
}

// 组件挂载后聚焦输入框并加载历史记录
onMounted(() => {
  if (inputRef.value) {
    inputRef.value.focus()
  }
  // 加载历史对话记录
  loadChatHistory()
  
  // 将图片查看函数挂载到window对象，以便在HTML中调用
  window.viewImage = viewImage
  // 添加键盘事件监听
  window.addEventListener('keydown', handleKeyDown)
})



// 组件卸载时清理
onUnmounted(() => {
  // 移除window对象上的viewImage函数
  window.viewImage = null
  // 移除键盘事件监听
  window.removeEventListener('keydown', handleKeyDown)
  // 移除拖动相关的事件监听
  window.removeEventListener('mousemove', onDrag)
  window.removeEventListener('mouseup', endDrag)
  window.removeEventListener('touchmove', onDrag)
  window.removeEventListener('touchend', endDrag)
})
</script>

<style scoped>
/* 图片查看器样式 */
.image-viewer-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  cursor: zoom-out;
}

.image-viewer-container {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 90%;
  height: 90%;
}

.image-viewer-content {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  border-radius: 8px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
  transition: transform 0.3s ease;
  cursor: grab;
  user-select: none;
}

.image-viewer-content:active {
  cursor: grabbing;
}

.image-loading-hide {
  opacity: 0;
}

.image-loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 1002;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 5px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: #fff;
  animation: spin 1s ease-in-out infinite;
}

.loading-text {
  color: white;
  margin-top: 10px;
  font-size: 16px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.image-viewer-controls {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  background-color: rgba(0, 0, 0, 0.6);
  border-radius: 20px;
  padding: 5px;
  z-index: 1001;
}

.viewer-control-button {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.2);
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 5px;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.viewer-control-button:hover {
  background-color: rgba(255, 255, 255, 0.4);
}

.viewer-control-button svg {
  width: 24px;
  height: 24px;
  color: white;
}

.close-button {
  background-color: rgba(255, 0, 0, 0.3);
}

.close-button:hover {
  background-color: rgba(255, 0, 0, 0.5);
}

/* 移动设备适配 */
@media (max-width: 768px) {
  .viewer-control-button {
    width: 36px;
    height: 36px;
  }
  
  .viewer-control-button svg {
    width: 20px;
    height: 20px;
  }
}

.message-image {
  cursor: zoom-in;
  transition: transform 0.2s ease;
  display: block; /* 确保图片是块级元素 */
  max-width: 100%; /* 确保图片不超出容器 */
  width: 300px; /* 统一宽度 */
  height: 200px; /* 统一高度 */
  object-fit: cover; /* 保持比例裁剪 */
  border-radius: 8px; /* 圆角边框 */
  margin: 10px 0; /* 上下间距 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); /* 轻微阴影效果 */
}

.message-image:hover {
  transform: scale(1.03);
}

/* 移动设备上的图片尺寸 */
@media (max-width: 768px) {
  .message-image {
    width: 250px;
    height: 170px;
  }
}

/* 图片加载错误样式 */
.image-error {
  color: #ff4d4f;
  font-size: 0.9rem;
  padding: 8px;
  margin: 8px 0;
  background-color: #fff2f0;
  border: 1px solid #ffccc7;
  border-radius: 4px;
  word-break: break-all;
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 76vh;
  background-color: #f0f4f8;
  font-family: 'Arial', sans-serif;
}

.chat-header {
  background-color: #2c3e50;
  color: white;
  padding: 16px 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 10;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 常用问题列表样式 */
.faq-container {
  background-color: #f8f9fa;
  padding: 12px 20px;
  border-bottom: 1px solid #e2e8f0;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

/* 响应式样式 */
@media (max-width: 768px) {
  .faq-container {
    padding: 10px 15px;
  }
  
  .faq-item {
    font-size: 12px;
    padding: 5px 10px;
  }
  
  .faq-mode-switch {
    width: 24px;
    height: 24px;
  }
  
  .faq-action-icon {
    width: 14px;
    height: 14px;
  }
}

.faq-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.faq-title {
  font-size: 14px;
  font-weight: 600;
  color: #2c3e50;
}

.faq-actions {
  display: flex;
  gap: 8px;
}

.faq-mode-switch {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  background-color: #f1f5f9;
  color: #64748b;
  transition: all 0.2s ease;
}

.faq-mode-switch:hover {
  background-color: #e2e8f0;
  color: #475569;
}

.faq-mode-switch.active {
  background-color: #3498db;
  color: white;
}

.faq-action-icon {
  width: 16px;
  height: 16px;
}

.faq-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  max-width: 100%;
  overflow-x: auto;
  padding-bottom: 4px;
  scrollbar-width: thin;
  scrollbar-color: #bdc3c7 #ecf0f1;
}

.faq-list::-webkit-scrollbar {
  height: 6px;
}

.faq-list::-webkit-scrollbar-track {
  background: #ecf0f1;
  border-radius: 10px;
}

.faq-list::-webkit-scrollbar-thumb {
  background-color: #bdc3c7;
  border-radius: 10px;
  transition: background-color 0.3s ease;
}

.faq-list::-webkit-scrollbar-thumb:hover {
  background-color: #95a5a6;
}

.faq-item {
  background-color: white;
  color: #3498db;
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 13px;
  cursor: pointer;
  border: 1px solid #e2e8f0;
  transition: all 0.2s ease;
  white-space: nowrap;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  gap: 6px;
}

.faq-item:hover {
  background-color: #3498db;
  color: white;
  border-color: #3498db;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(52, 152, 219, 0.2);
}

.delete-question {
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0.5;
  transition: all 0.2s ease;
  border-radius: 50%;
}

.delete-question:hover {
  opacity: 1;
  background-color: rgba(255, 255, 255, 0.2);
}

.delete-icon {
  width: 12px;
  height: 12px;
}

@media (max-width: 768px) {
  .delete-question {
    width: 14px;
    height: 14px;
  }
  
  .delete-icon {
    width: 10px;
    height: 10px;
  }
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.back-button {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.back-button:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.back-icon {
  width: 20px;
  height: 20px;
  color: white;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.header-actions {
  display: flex;
  align-items: center;
}

.clear-button {
  color: white;
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  opacity: 0.9;
  transition: all 0.2s ease;
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 20px;
  padding: 6px 12px;
}



.clear-button:hover {
  opacity: 1;
  background-color: rgba(255, 255, 255, 0.2);
}

.clear-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.clear-icon {
  width: 16px;
  height: 16px;
  margin-right: 4px;
}



.chat-body {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  scroll-behavior: smooth;
  position: relative;
}

.empty-chat {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #64748b;
}

.welcome-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  max-width: 500px;
  padding: 30px;
  background-color: white;
  border-radius: 16px;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.ai-avatar {
  width: 70px;
  height: 70px;
  background-color: #3498db;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
  color: white;
  box-shadow: 0 4px 10px rgba(52, 152, 219, 0.3);
}

.ai-avatar svg {
  width: 32px;
  height: 32px;
}

.welcome-text h3 {
  margin-bottom: 12px;
  color: #2c3e50;
  font-size: 22px;
  font-weight: 600;
}

.welcome-text p {
  color: #7f8c8d;
  line-height: 1.6;
  font-size: 16px;
}

.message-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.message-item {
  display: flex;
  gap: 12px;
  max-width: 80%;
}

.user-message {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.ai-message {
  align-self: flex-start;
}

.message-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.user-message .message-avatar {
  background-color: #3498db;
  color: white;
}

.ai-message .message-avatar {
  background-color: #ecf0f1;
  color: #2c3e50;
}

.message-avatar svg {
  width: 20px;
  height: 20px;
}

.message-content {
  background-color: white;
  padding: 12px 16px;
  border-radius: 12px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  position: relative;
}

.user-message .message-content {
  background-color: #3498db;
  color: white;
  border-radius: 12px 12px 2px 12px;
}

.ai-message .message-content {
  background-color: white;
  color: #2c3e50;
  border-radius: 12px 12px 12px 2px;
}

.error-message .message-content {
  background-color: #fef2f2;
  color: #b91c1c;
  border-left: 3px solid #e74c3c;
  border-radius: 12px 12px 12px 2px;
}

.error-message .message-avatar {
  background-color: #fdecec;
  color: #e74c3c;
}

.message-text {
  line-height: 1.5;
  word-break: break-word;
}

.message-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 4px;
}

.message-time {
  font-size: 12px;
  opacity: 0.7;
}

.message-actions {
  display: flex;
  gap: 8px;
}

.action-button {
  cursor: pointer;
  opacity: 0.7;
  transition: opacity 0.2s ease;
}

.action-button:hover {
  opacity: 1;
}

.action-icon {
  width: 16px;
  height: 16px;
}

/* 加载指示器 */
.loading-indicator {
  display: flex;
  justify-content: flex-start;
  margin: 16px 0;
  padding-left: 48px;
}

.typing-indicator {
  display: flex;
  align-items: center;
  gap: 4px;
  background-color: #ecf0f1;
  padding: 8px 16px;
  border-radius: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  background-color: #3498db;
  border-radius: 50%;
  display: inline-block;
  animation: typing 1.4s infinite ease-in-out both;
}

.typing-indicator span:nth-child(1) {
  animation-delay: 0s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0.6);
    opacity: 0.6;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.chat-footer {
  padding: 16px 20px;
  background-color: white;
  border-top: 1px solid #e2e8f0;
}

.input-container {
  display: flex;
  align-items: center;
  background-color: #ecf0f1;
  border-radius: 24px;
  padding: 10px 16px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.input-container:focus-within {
  box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.3), 0 2px 8px rgba(0, 0, 0, 0.1);
  background-color: #fff;
}

.chat-input {
  flex: 1;
  border: none;
  background: transparent;
  padding: 8px 0;
  resize: none;
  max-height: 120px;
  min-height: 24px;
  font-family: inherit;
  font-size: 14px;
  color: #1e293b;
  outline: none;
}

.chat-input:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.chat-input::placeholder {
  color: #94a3b8;
}

.send-button {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #3498db;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: white;
  transition: all 0.2s ease;
  margin-left: 8px;
  flex-shrink: 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.send-button:hover {
  background-color: #2980b9;
  transform: scale(1.05);
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.15);
}

.send-button.disabled {
  background-color: #bdc3c7;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.send-button svg {
  width: 18px;
  height: 18px;
}

/* 滚动条样式 */
.chat-body::-webkit-scrollbar {
  width: 6px;
}

.chat-body::-webkit-scrollbar-track {
  background: #ecf0f1;
  border-radius: 10px;
}

.chat-body::-webkit-scrollbar-thumb {
  background-color: #bdc3c7;
  border-radius: 10px;
  transition: background-color 0.3s ease;
}

.chat-body::-webkit-scrollbar-thumb:hover {
  background-color: #95a5a6;
}

/* 确保所有滚动条样式一致 */
::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-track {
  background: #ecf0f1;
  border-radius: 10px;
}

::-webkit-scrollbar-thumb {
  background-color: #bdc3c7;
  border-radius: 10px;
  transition: background-color 0.3s ease;
}

::-webkit-scrollbar-thumb:hover {
  background-color: #95a5a6;
}
</style>